//
//  NetworkTools.swift
//  AFNetworking的封装
//
//  Created by 万佳阳 on 16/8/3.
//  Copyright © 2016年 JYWan. All rights reserved.
//

import AFNetworking

//定义枚举类型
enum RequestType : String {
    case GET = "get"
    case POST = "post"
}

class NetworkTools: AFHTTPSessionManager {
    //let是线程安全的
    static let shareInstance : NetworkTools = {
        let tools = NetworkTools()
        tools.responseSerializer.acceptableContentTypes?.insert("text/html")
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        return tools
    }()
    
}

// MARK:- 封装网络请求
extension NetworkTools {
    func request(methodType : RequestType, urlString : String, parameters : [String : AnyObject], finished : (result : AnyObject?, error : NSError?) -> ()) {
        
        //定义成功的回调闭包
        let successBack = { (task : NSURLSessionDataTask, result : AnyObject?) in
            finished(result: result, error: nil)
        }
        
        //定义失败的闭包回调
        let failureBack = { (task : NSURLSessionDataTask?, error : NSError) in
            finished(result: nil, error: error)
        }
        
        
        if methodType == .GET {
            GET(urlString, parameters: parameters, progress: nil, success: successBack, failure: failureBack)
        } else {
            POST(urlString, parameters: parameters, progress: nil, success: successBack, failure: failureBack)
            
        }
    }
}

// MARK:- 请求accessToken
extension NetworkTools {
    func loadAccessToken(code : String, finished : (result : [String : AnyObject]?, error : NSError?) -> ()) {
        //获取请求的URLString
        let urlString = "https://api.weibo.com/oauth2/access_token"
        
        //获取请求的参数
        let parameters = ["client_id" : app_key, "client_secret" : app_secret, "grant_type" : "authorization_code", "redirect_uri" : redirect_uri, "code" : code]
        
        
        //发送请求
        request(.POST, urlString: urlString, parameters: parameters) { (result, error) in
            finished(result: result as? [String : AnyObject], error: error)
        }
    }
}

// MARK:- 请求用户的信息
extension NetworkTools {
    ///请求用户的信息
    func loadUserInfo(access_token : String, uid : String, finished : (result : [String : AnyObject]?, error : NSError?) -> ()) {
        //获取请求的URLString
        let urlString = "https://api.weibo.com/2/users/show.json"
        
        //获取请求参数
        let parameters = ["access_token" : access_token, "uid" : uid]
        
        //发送请求
        request(.GET, urlString: urlString, parameters: parameters) { (result, error) in
            finished(result: result as? [String : AnyObject], error: error)
        }
    }
}

// MARK:- 请求首页数据
extension NetworkTools {
    ///请求首页数据
    func loadStatuses(since_id : Int, max_id : Int, finished : (result : [[String : AnyObject]]?, error : NSError?) -> ()) {
        //获取URLString
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
        
        //获取参数
        let access_token = (JYUserAccountViewModel.shareInstance.userAccount?.access_token)!
        let parameters = ["access_token" : access_token, "since_id" : "\(since_id)", "max_id" : "\(max_id)"]
        
        //发送请求
        request(.GET, urlString: urlString, parameters: parameters) { (result, error) in
            //获取字典到数据
            guard let resultDict = result as? [String : AnyObject] else {
                finished(result: nil, error: error)
                return
            }
            
            finished(result: resultDict["statuses"] as? [[String : AnyObject]], error: error)
        }
        
    }
}

// MARK:- 发布一条微博
extension NetworkTools {
    ///发布一条微博
    func sendStatus(statusText : String, isSuccess : (isSuccess : Bool) -> ()) {
        //获取URLString
        let urlString = "https://api.weibo.com/2/statuses/update.json"
        
        //获取参数
        let parameters = ["access_token" : (JYUserAccountViewModel.shareInstance.userAccount?.access_token)!, "status" : statusText]
        
        //发送请求
        request(.POST, urlString: urlString, parameters: parameters) { (result, error) in
            if result != nil {
                isSuccess(isSuccess: true)
            } else {
                isSuccess(isSuccess: false)
            }
        }
        
    }
}

// MARK:- 发布一条微博并带有图片
extension NetworkTools {
    func sendStatus(statusText : String, image : UIImage, isSuccess : (isSuccess : Bool) -> ()) {
        //获取URLString
        let urlString = "https://api.weibo.com/2/statuses/upload.json"
        
        //获取参数
        let parameters = ["access_token" : (JYUserAccountViewModel.shareInstance.userAccount?.access_token)!, "status" : statusText]
        
        //发送请求
        POST(urlString, parameters: parameters, constructingBodyWithBlock: { (formData) in
            if let imageData = UIImageJPEGRepresentation(image, 0.8) {
                formData.appendPartWithFileData(imageData, name: "pic", fileName: "123.png", mimeType: "image/png")
            }
            }, progress: nil, success: { (_, _) in
                isSuccess(isSuccess: true)
            }) { (_, error) in
                print(error)
                isSuccess(isSuccess: false)
        }
    }
}



